package ift585.tp3;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.concurrent.Semaphore;

public class ResourceDownloader implements Runnable {

	private static final String IMAGE = "image";
	private static final String TEXT = "text";
	private static final String AUDIO = "audio";
	private static final String SUCCESFULL_REQUEST = "200";
	
	private String resource;
	private URL url;
	private HttpURLConnection conn = null;
	
	private static int compteurText = 0;
	private static int compteurImage = 0;
	private static int compteurAudio = 0;
	
	private static Semaphore mutexText = new Semaphore(1);
	private static Semaphore mutexImage = new Semaphore(1);
	private static Semaphore mutexAudio = new Semaphore(1);
	
	public ResourceDownloader(String resource) throws MalformedURLException, IOException {
		this.resource = resource;
		this.url = new URL(this.resource);
		conn = (HttpURLConnection) (this.url.openConnection());
	}

	@Override
	public void run() {
		String fileName = null;
		try {
			// ecrit le code html dans un fichier text et l'affiche a l'ecran
			InputStream content = null;
			
			if (pageIsValid()) {
				// Sauvegarde ressource courante
				if (conn.getContentType().startsWith(AUDIO)) {
					String format = conn.getContentType().split("/")[1];
					content = url.openStream();

					mutexAudio.acquire();
					fileName = "Audio" + compteurAudio + "." + format;
					compteurAudio++;
					mutexAudio.release();
				} else if (conn.getContentType().startsWith(IMAGE)) {
					String format = conn.getContentType().split("/")[1];
					content = url.openStream();

					mutexImage.acquire();
					fileName = "Image" + compteurImage + "." + format;
					compteurImage++;
					mutexImage.release();
				} else if (conn.getContentType().startsWith(TEXT)) {
					content = (InputStream) conn.getContent();

					mutexText.acquire();
					fileName = "Text" + compteurText + ".txt";
					compteurText++;
					mutexText.release();
				}
				
				System.out.println("***************************************");
				System.out.println("Showing header for request: " + resource);
				DisplayUtility.showHeader(conn);
				System.out.println("***************************************");
			}
			
			Utility.inputStreamToFile(content, fileName);
			Utility.popHtmlFile(fileName);
			content.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private boolean pageIsValid() {
		String[] statusLine = conn.getHeaderFields().get(null).get(0).split(" ");
		String errorCode = statusLine[1];
		return errorCode.equals(SUCCESFULL_REQUEST);
	}
}
